package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.domain.dbmodel.DevEquStore;
import cn.com.yx.ms.domain.dbmodel.SysOrg;
import cn.com.yx.ms.domain.sys.MoveCommonModel;
import cn.com.yx.ms.domain.sys.MoveDirectionType;
import cn.com.yx.ms.persistence.DevEquStoreMapper;
import cn.com.yx.ms.persistence.SysOrgMapper;
import cn.com.yx.ms.persistence.SysUserMapper;
import cn.com.yx.ms.service.ICommonService;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.BaseConstant;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class CommonServiceImpl implements ICommonService {

    @Resource
    private SysOrgMapper sysOrgMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private DevEquStoreMapper devEquStoreMapper;

//    @Override
//    public String getMaxNo(String tableName,String colName,String modelName) {
//        String MaxNo = "";
//
//
//        //拼接模块
//        MaxNo += modelName;
//
//        //获取当前时间
//        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
//        String date = dateFormater.format(new Date());
//        MaxNo += date;
//
//
//        //拼接手机号后4位
//        //MaxNo += mobile.substring(7);
//
//        //获取最大序列号
//        String max = sysOrgMapper.getMaxNo(tableName,colName,modelName,date);
//        if(StringUtils.isNoneBlank(max)) {
//            MaxNo += String.format("%04d", Integer.parseInt(max) + 1);
//        }
//        else{
//            MaxNo += String.format("%04d", 1);
//        }
//        return MaxNo;
//    }

    @Override
    public String getMaxNumber(String parentid) {
        String max = sysOrgMapper.getMaxNumber(parentid);
        int newNumber = 1;
        String parentNumber = "";

        if (StringUtils.isNoneBlank(max)) {
            int index = max.lastIndexOf(".");

            if (index != -1) {
                newNumber = Integer.parseInt(max.substring(index + 1)) + 1;
                parentNumber = max.substring(0, index + 1);
            }
        } else {
            //OrgModel parentOrg = sysOrgMapper.selectByPrimaryKey(parentid);
            SysOrg parentOrg = sysOrgMapper.selectByPrimaryKey(parentid);
            parentNumber = parentOrg.getNumber();
            parentNumber += ".";
        }

        String newMax = parentNumber + String.format("%03d", newNumber);
        return newMax;
    }

    @Override
    public ApiCode moveOrderIndex(String table,
                                  MoveDirectionType direct,
                                  String moveObjId,
                                  String parentId) {
        ApiCode apiCode = ApiCode.APP_100200;

        // 待排序的数据源
        List<MoveCommonModel> moveCommonModels=null;
        if(table.equals("dev_equ_store")){
           moveCommonModels=sysUserMapper.findDevMoveModels(table,parentId);
        }else if (table.equals("sys_user")){
           moveCommonModels=sysUserMapper.findUserMoveModels(table,parentId);
        }else if(table.equals("sc_file")){
           moveCommonModels=sysUserMapper.findScFileMoveModels(table,parentId);
        }else if(table.equals("gg_main")){
           moveCommonModels=sysUserMapper.findGgMoveModels(table,parentId);
        }else{
            moveCommonModels = sysUserMapper.findMoveModels(table, parentId);
        }
        MoveCommonModel source = null;
        MoveCommonModel target = null;
        int tempOrderindex = -1;

        // 重置序号,判断是否是设备的集合
        if (table.equals("dev_equ_store")){
            for (int i = 0; i < moveCommonModels.size(); i++) {
                sysUserMapper.updateDevMoveModel(moveCommonModels.get(i).getGuid(), Integer.toString(i), table);
            }
//            DevEquStore devEquStore= devEquStoreMapper.selectByguid(moveObjId);
//            if (direct.equals(MoveDirectionType.DOWN)){
//                //上移
//                List<DevEquStore> devEquStoreList=devEquStoreMapper.selectByorderindex(devEquStore.getOrderindex()+1);
//                //System.out.println("长度:"+devEquStoreList.size());
//                if (null == devEquStoreList || devEquStoreList.size()<1){
//                    return apiCode;
//                }else{
//                    devEquStore.setOrderindex(devEquStore.getOrderindex()+1);
//                    devEquStoreMapper.updateByPrimaryKey(devEquStore);
//                    for (DevEquStore devEquStore1:devEquStoreList) {
//                        devEquStore1.setOrderindex(devEquStore1.getOrderindex()-1);
//                        devEquStoreMapper.updateByPrimaryKey(devEquStore1);
//                    }
//                    return apiCode;
//                }
//            }else{
//                //下移
//                List<DevEquStore> devEquStoreList=devEquStoreMapper.selectByorderindex(devEquStore.getOrderindex()-1);
//                if (null == devEquStoreList || devEquStoreList.size()<1){
//                    return apiCode;
//                }else{
//                    devEquStore.setOrderindex(devEquStore.getOrderindex()-1);
//                    devEquStoreMapper.updateByPrimaryKey(devEquStore);
//                    for (DevEquStore devEquStore1:devEquStoreList) {
//                        devEquStore1.setOrderindex(devEquStore1.getOrderindex()+1);
//                        devEquStoreMapper.updateByPrimaryKey(devEquStore1);
//                    }
//                    return apiCode;
//                }
//            }
        }else{
            for (int i = 0; i < moveCommonModels.size(); i++) {
                sysUserMapper.updateMoveModel(moveCommonModels.get(i).getGuid(), Integer.toString(i), table);
            }
        }


        if (moveCommonModels != null && moveCommonModels.size() > 0 ) {

            for (int i = 0; i < moveCommonModels.size(); i++) {
                if (moveCommonModels.get(i).getGuid().equals(moveObjId)) {
                    source = moveCommonModels.get(i);
                    source.setOrderindex(i);
                    if (direct.equals(MoveDirectionType.UP)) {
                        if (i > 0) {
                            target = moveCommonModels.get(i - 1);
                            target.setOrderindex(i-1);
                        }
                    } else {
                        if (i < moveCommonModels.size() - 1) {
                            target = moveCommonModels.get(i + 1);
                            target.setOrderindex(i+1);
                        }
                    }
                    break;
                }
            }
        }

        if (source != null && target != null ) {


            // 交换
            tempOrderindex = source.getOrderindex();
            source.setOrderindex(target.getOrderindex());
            target.setOrderindex(tempOrderindex);
            // 更新排序号
            if(table.equals("dev_equ_store")){
                sysUserMapper.updateDevMoveModel(source.getGuid(), Integer.toString(source.getOrderindex()), table);
                sysUserMapper.updateDevMoveModel(target.getGuid(), Integer.toString(target.getOrderindex()), table);
            }else{
                sysUserMapper.updateMoveModel(source.getGuid(), Integer.toString(source.getOrderindex()), table);
                sysUserMapper.updateMoveModel(target.getGuid(), Integer.toString(target.getOrderindex()), table);
            }

        }

        return apiCode;
    }

    @Override
    public void generateQRCode(String gengeratePath, String imgName, String text) {
        String path = "";
        String qrcodeFilePath = "";
        try {

            if (!StringUtils.isNoneBlank(gengeratePath)) {
                path = BaseConstant.getUploadConfig().getFilepath();
            } else {
                path = gengeratePath;
            }

            int qrcodeWidth = 300;
            int qrcodeHeight = 300;
            String qrcodeFormat = "png";
            HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints);

            BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
            Random random = new Random();
//            File QrcodeFile = new File("F:\\qrcode\\" + random.nextInt() + "." + qrcodeFormat);
//            ImageIO.write(image, qrcodeFormat, QrcodeFile);

            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();//可创建多级目录，而mkdir()只能创建一级目录
            }

            Path QrcodeFile = new File(path + imgName + ".jpg").toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, QrcodeFile);
            // qrcodeFilePath = QrcodeFile.toAbsolutePath().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // return qrcodeFilePath;
    }
}